package rgb.power.led.controller;

import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class SerialHandler implements SerialPortEventListener {

    SerialPort serialPort;
    CommunicationHandler comHandler;
    OutputStream outputStream;
    InputStream inputStream;
    CommPort commPort;
    final static int FRAME_START_ID = 'S';

    public SerialHandler(CommunicationHandler comHandler) {
        this.comHandler = comHandler;
    }

    public String[] getAvailableSerialPorts() {

        String[] comPortsNames = new String[10];
        int i = 0;

        CommPortIdentifier portIdentifier;
        Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
        while (thePorts.hasMoreElements()) {

            CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();

            if (com.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                comPortsNames[i] = com.getName();
                i++;
            }
        }
        return (comPortsNames);
    }

    public void connect(String portName, int baudRate) throws Exception {

        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        DefaultListModel portsModel = new DefaultListModel();
        Enumeration ports = CommPortIdentifier.getPortIdentifiers();
        while (ports.hasMoreElements()) {
            portIdentifier = (CommPortIdentifier) ports.nextElement();
            portsModel.addElement(portIdentifier.getName());
            System.out.println(portIdentifier.getName());
        }
        commPort = portIdentifier.open(this.getClass().getName(), 2000);

        if (commPort instanceof SerialPort) {
            serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);


            outputStream = serialPort.getOutputStream();
            inputStream = serialPort.getInputStream();


            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);

        } else {
            System.out.println("Error: Only serial ports are handled by this example.");
        }
    }

    public void serialEvent(SerialPortEvent arg0) {

        int byte_r;
        

        try {
            //comHandler.recievePacket(inputStream.read());            // TODO, update with new class. 
            System.out.print("R 0x" + Integer.toHexString(inputStream.read()));
        } catch (IOException ex) {
            Logger.getLogger(SerialHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void sendPacket(byte[] serialOutputBuffer) {

        try {


            for (int i = 0; i < serialOutputBuffer.length; i++) {
                outputStream.write(serialOutputBuffer[i]);
            }



            System.out.print("Output Packet:");
            for (int i = 0; i < serialOutputBuffer.length; i++) {
                System.out.print(" 0x" + Integer.toHexString(serialOutputBuffer[i]));
            }
            System.out.println("");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }
    
    public void disconnect (){
        
        commPort.close();       
        
    }
    
}
